import { store } from "quasar/wrappers";
import { createPinia } from "pinia";

import { shopStore } from "./shop";

import { LocalStorage } from "quasar";

import { toRaw } from "vue";

// 数据存储本地
const setStorage = (key, value) => {
  LocalStorage.set(key, JSON.stringify(value));
};
// 获取本地数据
const getStorage = (key) => {
  const data = LocalStorage.getItem(key);
  return data ? JSON.parse(data) : {};
};

const piniaPlugin = (context) => {
  const { store } = context;
  // $subscribe state值发生变化时会执行传入的回调
  store.$subscribe(() => {
    // 每次修改值的时候更新localStorage数据
    setStorage(`pinia-${store.$id}`, toRaw(store.$state));
  });
  // 每次构建项目的时候从本地存储取值
  const data = getStorage(`pinia-${store.$id}`);
  // 并将取的值赋给state;
  return {
    ...data,
  };
};

/*
 * If not building with SSR mode, you can
 * directly export the Store instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Store instance.
 */
export default store((/* { ssrContext } */) => {
  const pinia = createPinia();

  // You can add Pinia plugins here
  // pinia.use(SomePiniaPlugin)
  pinia.use(piniaPlugin);

  return pinia;
});
